package com.fxwater.websocket.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fxwater.websocket.domain.RedisCacheInfo;
import com.fxwater.websocket.domain.RedisCacheManager;
import com.fxwater.websocket.init.ScheduledTaskInitializer;
import com.fxwater.websocket.job.SelectRealData;
import com.fxwater.websocket.mapper.SocketFlushIntervalMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import javax.websocket.Session;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class OneThread extends Thread {

    private Session session;

    private List<String> currentMessage;

    private int currentIndex;

    private String seceneId;

    private SocketFlushIntervalMapper socketFlushIntervalMapper;

    private final String[] measureObjects = SelectRealData.selectRealDataInfo();


    private RedisTemplate<String, Serializable> redisTemplate;

    private Logger logger =  LoggerFactory.getLogger(ScheduledTaskInitializer.class);

    public OneThread(Session session,RedisTemplate<String, Serializable> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.session = session;
        currentMessage = new ArrayList<String>();
        currentIndex = 0;//此时是0条消息
    }

    @Override
    public void run() {
        while (true) {
            String realSceneId =null;
            try {
                String sessionId = this.session.getId();
                if(redisTemplate==null){
                    redisTemplate = SpringBeanFinder.findBean("stringRedisTemplate");
                }
                if(redisTemplate.hasKey(sessionId)){
                    this.seceneId = (String) redisTemplate.opsForValue().get(sessionId);
                }
                if(StrUtil.isNotEmpty(this.seceneId)){
                    realSceneId = this.seceneId;
                    String[] sceneParams = new String[]{};
                    if(this.seceneId.contains("_")){
                        sceneParams = this.seceneId.split("_");
                        realSceneId = sceneParams[0];
                    }

                    if(StrUtil.isNotEmpty(realSceneId)){
                        if(!"THIRD".equals(realSceneId)){
                            List<RedisCacheInfo> redisCacheInfos = RedisCacheManager.getInstance().getCacheInfoBySceneIId(realSceneId);
                            if(CollectionUtil.isNotEmpty(redisCacheInfos)){
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("scenName",realSceneId);
                                final String[] params = sceneParams;
                                redisCacheInfos.forEach(redisCacheInfo -> {
                                    String groupId = redisCacheInfo.getGroupId();
                                    String keyId = redisCacheInfo.getKeyId();
                                    String redisPrefix = redisCacheInfo.getRedisPrefix();
                                    String redisKey = KeyUtil.getRedisKey(redisPrefix,groupId,keyId,params);
                                    if(redisTemplate.hasKey(redisKey)){
                                        String value = (String) redisTemplate.opsForValue().get(redisKey) ;
                                        if(value.startsWith("\"") && value.endsWith("\"")){
                                            value = value.substring(1,value.length()-1);
                                        }
                                        Object v = value;
                                        if(JSONUtil.isJsonObj(value)){
                                            v = JSONUtil.parseObj(value);
                                        } else if(JSONUtil.isJsonArray(value)){
                                            v = JSONUtil.parseArray(value);
                                        } else if(JSONUtil.isJson(value)){
                                            v = JSONUtil.parse(value);
                                        }
                                        if(StrUtil.isNotEmpty(groupId)){
                                            if(StrUtil.isNotEmpty(keyId)){
                                                if(jsonObject.containsKey(groupId)){
                                                    JSONObject jsonObject1 = jsonObject.getJSONObject(groupId);
                                                    jsonObject1.put(keyId,v);
                                                    jsonObject.put(groupId,jsonObject1);
                                                } else {
                                                    JSONObject jsonObject1 = new JSONObject();
                                                    jsonObject1.put(keyId,v);
                                                    jsonObject.put(groupId,jsonObject1);
                                                }
                                            } else{
                                                jsonObject.put(groupId,v);
                                            }
                                        }

                                    }
                                });
                                session.getBasicRemote().sendText(jsonObject.toString());
                                logger.info("向客户<{}>,场景{}，发送数据信息:{}",session.getId(),sessionId,jsonObject);
                            }
                        } else  if("THIRD".equals(realSceneId)){
                            String[] keyIds =  new String[]{"VAL","item_name","unit_zn","unit_flag","LAST_UPDATE","VAL_"};
                            if(measureObjects!=null && measureObjects.length>0){
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("scenName",realSceneId);
                                final String[] params = sceneParams;
                                for(String groupId:measureObjects){
                                    for(String keyId:keyIds){
                                        String redisPrefix = "THIRD_$SCENIID.1_$DATE";
                                        String redisKey = KeyUtil.getRedisKey(redisPrefix,groupId,keyId,params);
                                        if(redisTemplate.hasKey(redisKey)){
                                            String value = (String) redisTemplate.opsForValue().get(redisKey) ;
                                            if(value.startsWith("\"") && value.endsWith("\"")){
                                                value = value.substring(1,value.length()-1);
                                            }
                                            Object v = value;
                                            if(JSONUtil.isJsonObj(value)){
                                                v = JSONUtil.parseObj(value);
                                            } else if(JSONUtil.isJsonArray(value)){
                                                v = JSONUtil.parseArray(value);
                                            } else if(JSONUtil.isJson(value)){
                                                v = JSONUtil.parse(value);
                                            }
                                            if(StrUtil.isNotEmpty(groupId)){
                                                if(StrUtil.isNotEmpty(keyId)){
                                                    if(jsonObject.containsKey(groupId)){
                                                        JSONObject jsonObject1 = jsonObject.getJSONObject(groupId);
                                                        jsonObject1.put(keyId,v);
                                                        jsonObject.put(groupId,jsonObject1);
                                                    } else {
                                                        JSONObject jsonObject1 = new JSONObject();
                                                        jsonObject1.put(keyId,v);
                                                        jsonObject.put(groupId,jsonObject1);
                                                    }
                                                } else{
                                                    jsonObject.put(groupId,v);
                                                }
                                            }

                                        }
                                    }
                                }
                                session.getBasicRemote().sendText(jsonObject.toString());
                                logger.info("向客户<{}>,场景{}，发送数据信息:{}",session.getId(),sessionId,jsonObject);
                            }
                        }
                    } else {
                        logger.info("向客户<{}>,场景{}，发送数据信息:尚未获取场景信息");
                        session.getBasicRemote().sendText("尚未获取场景信息");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(socketFlushIntervalMapper==null){
                    socketFlushIntervalMapper = SpringBeanFinder.findBean(SocketFlushIntervalMapper.class);
                }
                String interval  = socketFlushIntervalMapper.selectSocketFlushIntervalBySceneId(realSceneId);
                logger.info("向客户<{}>,场景{}，延时{}毫秒重新发送消息",session.getId(),realSceneId,interval);
                if(StrUtil.isNotEmpty(interval)){
                    Thread.sleep(Integer.parseInt(interval));
                } else {
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

}
